package service

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"tFilm4/internal/model"
	"tFilm4/internal/service/internal/dao"
	"tFilm4/internal/service/internal/do"
)

type sComment struct{}

var insComment = sComment{}

func Comment() *sComment {
	return &insComment
}

func (s *sComment) CreateComment(ctx context.Context, in model.CreateCommentInput) (err error) {
	return dao.Comment.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err := dao.Comment.Ctx(ctx).Data(do.Comment{
			UserId:  in.UserId,
			MovieId: in.MovieId,
			Content: in.Content,
		}).Insert()
		return err
	})
}

func (s *sComment) GetCommentByMovieId(ctx context.Context, movieId int) (count int, commentInfos []model.CommentInfo, err error) {
	err = dao.Comment.Ctx(ctx).Where("movie_id", movieId).ScanList(&commentInfos, "Comment")
	if err != nil {
		return
	}
	err = dao.User.Ctx(ctx).Where("user_id", gdb.ListItemValuesUnique(&commentInfos, "Comment", "UserId")).ScanList(&commentInfos, "User", "Comment", "user_id:UserId")
	if err != nil {
		return
	}
	err = dao.Movie.Ctx(ctx).Where("movie_id", gdb.ListItemValuesUnique(&commentInfos, "Comment", "MovieId")).ScanList(&commentInfos, "Movie", "Comment", "movie_id:MovieId")
	if err != nil {
		return
	}
	count, err = dao.Comment.Ctx(ctx).Where("movie_id", movieId).Count()
	return
}
